import { BrowserWindow } from "electron";
import { getTargetWindow } from "./CreateWindow";
import { IChildWindowParams } from "../types/window";
import path from "node:path";
import { RENDERER_DIST, VITE_DEV_SERVER_URL, __dirname } from "../main";

export function createChildWindow(params: IChildWindowParams) {
  let mainWindow = getTargetWindow("home"); // BrowserWindow 类型
  if (!mainWindow) return;
  const { x, y, width, height } = mainWindow.getBounds();
  let childWindow = new BrowserWindow({
    width: 400,
    height,
    x: x + width,
    y,
    parent: mainWindow,
    resizable: false,
    frame: false,
    modal: false, // 取消模态，不锁定
    show: true, // 创建后立即显示
    webPreferences: {
      preload: path.join(__dirname, "preload.mjs"),
      contextIsolation: true,
      nodeIntegration: false,
    },
  });
  childWindow.setTitle(params.title);
  if (VITE_DEV_SERVER_URL) {
    childWindow.loadURL(VITE_DEV_SERVER_URL + params.path).catch(console.error);
    childWindow.webContents.openDevTools();
  } else {
    childWindow
      .loadFile(path.join(RENDERER_DIST, "index.html"), {
        hash: params.path,
      })
      .catch(console.error);
  }

  const syncInterval = setInterval(() => {
    if (mainWindow.isDestroyed() || childWindow.isDestroyed()) {
      clearInterval(syncInterval);
      return;
    }
    const { x, y, width, height } = mainWindow.getBounds();
    childWindow.setBounds(
      {
        x: x + width,
        y: y,
        width: 350,
        height: height,
      },
      false,
    ); // 第二个参数 false 表示不动画，立刻同步
  }, 16); // 每 16ms，大概就是一帧（60fps）

  // 父窗口关闭时也关闭子窗口
  mainWindow.on("closed", () => {
    if (syncInterval) clearInterval(syncInterval);
    if (childWindow && !childWindow.isDestroyed()) {
      childWindow.close();
    }
  });

  // 阻止默认跳转
  childWindow.webContents.on("will-navigate", (event, _url) => {
    event.preventDefault();
  });

  childWindow.webContents.setWindowOpenHandler(() => {
    return { action: "deny" }; // 阻止新窗口
  });

  childWindow.on("closed", () => {
    if (syncInterval) clearInterval(syncInterval);
    childWindow.removeAllListeners();
    childWindow = null as any; // 安全释放引用
  });
}
